<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    var prevPermOpt1 = function (arr) {
      const n = arr.length;
      for (let i = n - 2; i >= 0; i--) {
        if (arr[i] > arr[i + 1]) {
          let j = n - 1;
          while (arr[j] >= arr[i] || arr[j] == arr[j - 1]) {
            j--;
          }
          let temp = arr[i];
          arr[i] = arr[j];
          arr[j] = temp;
          break;
        }
      }
      return arr;

    };
    console.log(prevPermOpt1([3, 2, 1]))
  </script>
</body>

</html>